package com.wjqy.controller;

import com.alibaba.fastjson.JSONObject;
import com.wjqy.entity.Comment;
import com.wjqy.entity.CommonReturnEntity;
import com.wjqy.entity.User;
import com.wjqy.service.UserService;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;

@RestController
public class userController {

    @Autowired
    private UserService userService;

    /*@MethodName: publishComment
     * @Author: man
     * @Description: 用户评论
     * @Date:  10:59 2020/7/5
     * @Param: [files, request]
     * @Return: com.wjqy.entity.CommonReturnEntity
     **/
    @RequestMapping(value = "comment", method = RequestMethod.POST)
    public CommonReturnEntity publishComment(MultipartFile[] files, HttpServletRequest request, Comment comment) throws IOException {
        // 判断文件是否为空，空则返回失败页面
        if (files.length > 0) {
            // 获取文件存储路径（绝对路径）
            String path = request.getServletContext().getRealPath("/WEB-INF/pages/static/upload");
           /* File dir = new File(path);
            if (!dir.exists()){
                dir.mkdir();
            }*/
            StringBuilder picList = new StringBuilder();
            for (MultipartFile file : files) {
                // 获取原文件名
                String fileName = file.getOriginalFilename();
                String uuid = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
                fileName = uuid + "_" + fileName;
                picList.append(fileName).append(";");
                // 创建文件实例
                File filePath = new File(path, fileName);
                // 写入文件
                file.transferTo(filePath);
            }
            comment.setPics(picList.toString());
            picList = null;
        }
        comment.setUserId((Integer) request.getSession().getAttribute("userId"));
        int i = userService.insertComment(comment);
        if (i<1){
            return CommonReturnEntity.fail("评论失败！");
        }
        return CommonReturnEntity.success("评论成功！");
    }

    @RequestMapping("usecdk")
    public CommonReturnEntity useCDK(String cdk, HttpSession session){
        Integer userId = (Integer) session.getAttribute("userId");
        if (userService.useCDK(cdk,userId)) {
            return CommonReturnEntity.success("兑换成功");
        }
        return CommonReturnEntity.fail("兑换失败");
    }

    @RequestMapping("bindsuperior/{code}")
    public CommonReturnEntity bindSuperior(@PathVariable("code") String code,HttpSession session ){
        User user = (User) session.getAttribute("user");
        if (user.getSuperior()!=null){
            return CommonReturnEntity.fail("该用户已经绑定过上级");
        }
        if (userService.bindSuperior(user, code)){
            return CommonReturnEntity.success("绑定成功");
        }else {
            return CommonReturnEntity.fail("用户绑定失败！");
        }
    }

    @RequestMapping("getopenid")
    public CommonReturnEntity getOpenId(String code) throws IOException {
        String appid="wx1e2307495c06f207";
        String secret="cc69a57e973ae87ea0d32db57e83f677";
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid="+appid+"&secret="+secret+"&js_code="+code+"&grant_type=authorization_code";
        HttpClient client = HttpClientBuilder.create().build();
        HttpGet get = new HttpGet(url);
        HttpResponse response = client.execute(get);
        HttpEntity entity = response.getEntity();
        String s = EntityUtils.toString(entity);
        JSONObject info = JSONObject.parseObject(s);
        String openid = info.getString("openid");
        return CommonReturnEntity.success(openid);
    }


    /*@MethodName: userInfo
     * @Author: man
     * @Description:
     * @Date:  14:55 2020/7/8
     * @Param: name pic
     * @Return: com.wjqy.entity.CommonReturnEntity
    **/
    @RequestMapping("userinfo")
    public CommonReturnEntity userInfo(@RequestParam Map<String,String> map){
        return CommonReturnEntity.success(map);
    }
}


